{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 align=\"center\">Introduction to SimpleITKv4 Registration - Continued</h1>\n",
    "\n",
    "\n",
    "## ITK v4 Registration Components \n",
    "<img src=\"ITKv4RegistrationComponentsDiagram.svg\" style=\"width:700px\"/><br><br>\n",
    "\n",
    "\n",
    "Before starting with this notebook, please go over the first introductory notebook found [here](60_Registration_Introduction.ipynb). \n",
    "\n",
    "In this notebook we will visually assess registration by viewing the overlap between images using external viewers.\n",
    "The two viewers we recommend for this task are [ITK-SNAP](http://www.itksnap.org) and [3D Slicer](http://www.slicer.org/). ITK-SNAP supports concurrent linked viewing between multiple instances of the program. 3D Slicer supports concurrent viewing of multiple volumes via alpha blending."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "library(SimpleITK)\n",
    "\n",
    "# If the environment variable SIMPLE_ITK_MEMORY_CONSTRAINED_ENVIRONMENT is set, this will override the ReadImage\n",
    "# function so that it also resamples the image to a smaller size (testing environment is memory constrained).\n",
    "source(\"setup_for_testing.R\")\n",
    "\n",
    "# Utility method that either downloads data from the Girder repository or\n",
    "# if already downloaded returns the file name for reading from disk (cached data).\n",
    "source(\"downloaddata.R\")\n",
    "\n",
    "# Always write output to a separate directory, we don't want to pollute the source directory. \n",
    "OUTPUT_DIR = \"Output\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Utility functions\n",
    "A number of utility functions, saving a transform and corresponding resampled image, callback for selecting a \n",
    "DICOM series from several series found in the same directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "#\n",
    "# Write the given transformation to file, resample the moving_image onto the fixed_images grid and save the\n",
    "# result to file.\n",
    "# @param transform (SimpleITK Transform): transform that maps points from the fixed image coordinate system to the moving.\n",
    "# @param fixed_image (SimpleITK Image): resample onto the spatial grid defined by this image.\n",
    "# @param moving_image (SimpleITK Image): resample this image.\n",
    "# @param outputfile_prefix (string): transform is written to outputfile_prefix.tfm and resampled image is written to \n",
    "#                                    outputfile_prefix.mha.\n",
    "#                             \n",
    "save_transform_and_image <- function(transform, fixed_image, moving_image, outputfile_prefix)\n",
    "{\n",
    "    resample <- ResampleImageFilter()\n",
    "    resample$SetReferenceImage(fixed_image)\n",
    "    \n",
    "    # SimpleITK supports several interpolation options, we go with the simplest that gives reasonable results.     \n",
    "    resample$SetInterpolator(\"sitkLinear\")  \n",
    "    resample$SetTransform(transform)\n",
    "    WriteImage(resample$Execute(moving_image), paste0(outputfile_prefix,\".mha\"))\n",
    "    WriteTransform(transform, paste0(outputfile_prefix,\".tfm\"))\n",
    "}\n",
    "\n",
    "#\n",
    "# Get the DICOM tag values for a given file.\n",
    "# @param file_name (string): Name of the DICOM file.\n",
    "# @param tags (list(string)): List of strings containing the DICOM tags of interest. These are not the human readable\n",
    "#                             values (i.e. They are of the form 0010|0010).\n",
    "# @return (list(string)): List of strings containing the value of each of the DICOM tags.\n",
    "#                             \n",
    "get_DICOM_tag_values <- function(file_name, tags)\n",
    "{    \n",
    "    img <- ReadImage(file_name)\n",
    "    lapply(tags, function(tag) img$GetMetaData(tag))\n",
    "}\n",
    "\n",
    "#\n",
    "# Get a dataframe containing DICOM tag information for the given set of series.\n",
    "#\n",
    "display_DICOM_information <- function(series_file_lists)\n",
    "{               \n",
    "    tags_to_print <- list(c('0010|0010', 'Patient name'), \n",
    "                          c('0008|0060', 'Modality'),\n",
    "                          c('0008|0021', 'Series date'),\n",
    "                          c('0008|0031', 'Series time'),\n",
    "                          c('0008|0070', 'Manufacturer'))\n",
    "    tags_to_print <- c('0010|0010', '0008|0060', '0008|0021', '0008|0031', '0008|0070')\n",
    "    names(tags_to_print) <- c('Patient name', 'Modality', 'Series date', 'Series time', 'Manufacturer')\n",
    "    data <- lapply(series_file_lists, \n",
    "                   function(x, tag_list) get_DICOM_tag_values(x[1], tag_list), \n",
    "                   tag_list=tags_to_print)\n",
    "    df <- as.data.frame(do.call(rbind, data))\n",
    "    df <- cbind(SeriesID=rownames(df), df)\n",
    "    rownames(df) <- NULL\n",
    "    return(df)\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading Data\n",
    "\n",
    "In this notebook we will work with CT and MR scans of the CIRS 057A multi-modality abdominal phantom. The scans are multi-slice DICOM images. The data is stored in a zip archive which is automatically retrieved and extracted when we request a file which is part of the archive."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "data_directory <- dirname(fetch_data(\"CIRS057A_MR_CT_DICOM/readme.txt\"))\n",
    "# Directory contains multiple DICOM studies/series, store the file names in a list\n",
    "reader <- ImageSeriesReader()\n",
    "series_IDs <- ImageSeriesReader_GetGDCMSeriesIDs(data_directory) #vector with strings/series IDs\n",
    "names(series_IDs) <- series_IDs\n",
    "series_file_names <- lapply(series_IDs, \n",
    "                            function(sid, data_dir) ImageSeriesReader_GetGDCMSeriesFileNames(data_dir, sid),\n",
    "                            data_dir=data_directory)\n",
    "display_DICOM_information(series_file_names)       "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# Based on the DICOM image meta-information, select the fixed and moving images to register.\n",
    "series_index_fixed_image <- \"1.2.840.113619.2.290.3.3233817346.783.1399004564.515\"\n",
    "series_index_moving_image <- \"1.3.12.2.1107.5.2.18.41548.30000014030519285935000000933\"\n",
    "\n",
    "# Actually read the data based on the user's selection.\n",
    "reader$SetFileNames(series_file_names[[series_index_fixed_image]])\n",
    "fixed_image <- reader$Execute()\n",
    "    \n",
    "reader$SetFileNames(series_file_names[[series_index_moving_image]])\n",
    "moving_image <- reader$Execute()\n",
    "\n",
    "# Save images to file and view overlap using external viewer.\n",
    "WriteImage(fixed_image, file.path(OUTPUT_DIR, \"fixedImage.mha\"))\n",
    "WriteImage(moving_image, file.path(OUTPUT_DIR, \"preAlignment.mha\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Initial Alignment\n",
    "\n",
    "A reasonable guesstimate for the initial translational alignment can be obtained by using\n",
    "the CenteredTransformInitializer (functional interface to the CenteredTransformInitializerFilter). \n",
    "\n",
    "The resulting transformation is centered with respect to the fixed image and the\n",
    "translation aligns the centers of the two images. There are two options for\n",
    "defining the centers of the images, either the physical centers\n",
    "of the two data sets (GEOMETRY), or the centers defined by the intensity \n",
    "moments (MOMENTS).\n",
    "\n",
    "Two things to note about this filter, it requires the fixed and moving image \n",
    "have the same type even though it is not algorithmically required, and its\n",
    "return type is the generic SimpleITK.Transform."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "initial_transform <- CenteredTransformInitializer(Cast(fixed_image,moving_image$GetPixelID()), \n",
    "                                                  moving_image, \n",
    "                                                  Euler3DTransform(), \n",
    "                                                  \"GEOMETRY\")\n",
    "\n",
    "# Save moving image after initial transform and view overlap using external viewer.\n",
    "save_transform_and_image(initial_transform, fixed_image, moving_image, file.path(OUTPUT_DIR, \"initialAlignment\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "Look at the transformation, what type is it?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(initial_transform)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Final registration"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "### Version 1\n",
    "<ul>\n",
    "<li> Single scale (not using image pyramid).</li>\n",
    "<li> Initial transformation is not modified in place.</li>\n",
    "</ul>\n",
    "\n",
    "<ol>\n",
    "<li>\n",
    "Illustrate the need for scaling the step size differently for each parameter:\n",
    "<ul>\n",
    "<li> SetOptimizerScalesFromIndexShift - estimated from maximum shift of voxel indexes (only use if data is isotropic).</li>\n",
    "<li> SetOptimizerScalesFromPhysicalShift - estimated from maximum shift of physical locations of voxels.</li>\n",
    "<li> SetOptimizerScalesFromJacobian - estimated from the averaged squared norm of the Jacobian w.r.t. parameters.</li>\n",
    "</ul>\n",
    "</li>\n",
    "<li>\n",
    "Look at the optimizer's stopping condition to ensure we have not terminated prematurely.\n",
    "</li>\n",
    "</ol>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "registration_method <- ImageRegistrationMethod()\n",
    "\n",
    "registration_method$SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "registration_method$SetMetricSamplingStrategy(\"RANDOM\")\n",
    "registration_method$SetMetricSamplingPercentage(0.01)\n",
    "\n",
    "registration_method$SetInterpolator(\"sitkLinear\")\n",
    "\n",
    "registration_method$SetOptimizerAsGradientDescent(learningRate=1.0, numberOfIterations=100)\n",
    "# Scale the step size differently for each parameter, this is critical!!!\n",
    "registration_method$SetOptimizerScalesFromPhysicalShift() \n",
    "\n",
    "registration_method$SetInitialTransform(initial_transform, inPlace=FALSE)\n",
    "    \n",
    "final_transform_v1 = registration_method$Execute(Cast(fixed_image, \"sitkFloat32\"), \n",
    "                                                 Cast(moving_image, \"sitkFloat32\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cat(paste0(\"Optimizer\\'s stopping condition, \",registration_method$GetOptimizerStopConditionDescription(),\"\\n\"))\n",
    "cat(paste0(\"Final metric value: \",registration_method$GetMetricValue()))\n",
    "\n",
    "# Save moving image after registration and view overlap using external viewer.\n",
    "save_transform_and_image(final_transform_v1, fixed_image, moving_image, file.path(OUTPUT_DIR, \"finalAlignment-v1\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Look at the final transformation, what type is it?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(final_transform_v1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Version 1.1\n",
    "\n",
    "The previous example illustrated the use of the ITK v4 registration framework in an ITK v3 manner. We only referred to a single transformation which was what we optimized.\n",
    "\n",
    "In ITK v4 the registration method accepts three transformations (if you look at the diagram above you will only see two transformations, Moving transform represents $T_{opt} \\circ T_m$):\n",
    "<ul>\n",
    "<li>\n",
    "SetInitialTransform, $T_{opt}$ - composed with the moving initial transform, maps points from the virtual image domain to the moving image domain, modified during optimization. \n",
    "</li>\n",
    "<li>\n",
    "SetFixedInitialTransform $T_f$- maps points from the virtual image domain to the fixed image domain, never modified.\n",
    "</li>\n",
    "<li>\n",
    "SetMovingInitialTransform $T_m$- maps points from the virtual image domain to the moving image domain, never modified.\n",
    "</li>\n",
    "</ul>\n",
    "\n",
    "The transformation that maps points from the fixed to moving image domains is thus: $^M\\mathbf{p}  = T_{opt}(T_m(T_f^{-1}(^F\\mathbf{p})))$\n",
    "\n",
    "We now modify the previous example to use $T_{opt}$ and $T_m$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "registration_method <- ImageRegistrationMethod()\n",
    "registration_method$SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "registration_method$SetMetricSamplingStrategy(\"RANDOM\")\n",
    "registration_method$SetMetricSamplingPercentage(0.01)\n",
    "registration_method$SetInterpolator(\"sitkLinear\")\n",
    "registration_method$SetOptimizerAsGradientDescent(learningRate=1.0, numberOfIterations=100)\n",
    "registration_method$SetOptimizerScalesFromPhysicalShift()\n",
    "\n",
    "# Set the initial moving and optimized transforms.\n",
    "optimized_transform <- Euler3DTransform()    \n",
    "registration_method$SetMovingInitialTransform(initial_transform)\n",
    "registration_method$SetInitialTransform(optimized_transform)\n",
    "\n",
    "dev_null <- registration_method$Execute(Cast(fixed_image, \"sitkFloat32\"), \n",
    "                                        Cast(moving_image, \"sitkFloat32\"))\n",
    "\n",
    "# Need to compose the transformations after registration.\n",
    "final_transform_v11 <- Transform(optimized_transform)\n",
    "dev_null <- final_transform_v11$AddTransform(initial_transform)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cat(paste0(\"Optimizer\\'s stopping condition, \",registration_method$GetOptimizerStopConditionDescription(),\"\\n\"))\n",
    "cat(paste0(\"Final metric value: \",registration_method$GetMetricValue()))\n",
    "\n",
    "# Save moving image after registration and view overlap using external viewer.\n",
    "save_transform_and_image(final_transform_v11, fixed_image, moving_image, file.path(OUTPUT_DIR, \"finalAlignment-v1.1\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Look at the final transformation, what type is it? Why is it different from the previous example?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(final_transform_v11)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Version 2\n",
    "\n",
    "<ul>\n",
    "<li> Multi scale - specify both scale, and how much to smooth with respect to original image.</li>\n",
    "<li> Initial transformation modified in place, so in the end we have the same type of transformation in hand.</li>\n",
    "</ul>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "registration_method <- ImageRegistrationMethod()\n",
    "\n",
    "registration_method$SetMetricAsMattesMutualInformation(numberOfHistogramBins=50)\n",
    "registration_method$SetMetricSamplingStrategy(\"RANDOM\")\n",
    "registration_method$SetMetricSamplingPercentage(0.01)\n",
    "\n",
    "registration_method$SetInterpolator(\"sitkLinear\")\n",
    "   \n",
    "registration_method$SetOptimizerAsGradientDescent(learningRate=1.0, numberOfIterations=100) #, estimateLearningRate=registration_method.EachIteration)\n",
    "registration_method$SetOptimizerScalesFromPhysicalShift() \n",
    "\n",
    "final_transform <- Euler3DTransform(initial_transform)\n",
    "registration_method$SetInitialTransform(final_transform)\n",
    "registration_method$SetShrinkFactorsPerLevel(shrinkFactors = c(4,2,1))\n",
    "registration_method$SetSmoothingSigmasPerLevel(smoothingSigmas = c(2,1,0))\n",
    "registration_method$SmoothingSigmasAreSpecifiedInPhysicalUnitsOn()\n",
    "\n",
    "dev_null <- registration_method$Execute(Cast(fixed_image, \"sitkFloat32\"), \n",
    "                                        Cast(moving_image, \"sitkFloat32\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "cat(paste0(\"Optimizer\\'s stopping condition, \",registration_method$GetOptimizerStopConditionDescription(),\"\\n\"))\n",
    "cat(paste0(\"Final metric value: \",registration_method$GetMetricValue()))\n",
    "\n",
    "# Save moving image after registration and view overlap using external viewer.\n",
    "save_transform_and_image(final_transform, fixed_image, moving_image, file.path(OUTPUT_DIR, \"finalAlignment-v2\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Look at the final transformation, what type is it?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(final_transform)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "R",
   "language": "R",
   "name": "ir"
  },
  "language_info": {
   "codemirror_mode": "r",
   "file_extension": ".r",
   "mimetype": "text/x-r-source",
   "name": "R",
   "pygments_lexer": "r",
   "version": "3.2.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
